package com.cskaoyan.order.service.impl;

import com.cskaoyan.mall.commons.constant.SysRetCodeConstants;
import com.cskaoyan.mall.commons.exception.BizException;
import com.cskaoyan.order.biz.TransOutboundInvoker;
import com.cskaoyan.order.biz.context.AbsTransHandlerContext;
import com.cskaoyan.order.biz.factory.OrderProcessPipelineFactory;
import com.cskaoyan.order.constant.OrderConstants;
import com.cskaoyan.order.constant.OrderRetCode;
import com.cskaoyan.order.dal.entitys.Order;
import com.cskaoyan.order.dal.entitys.OrderItem;
import com.cskaoyan.order.dal.entitys.OrderShipping;
import com.cskaoyan.order.dal.entitys.Stock;
import com.cskaoyan.order.dal.persistence.OrderItemMapper;
import com.cskaoyan.order.dal.persistence.OrderMapper;
import com.cskaoyan.order.dal.persistence.OrderShippingMapper;
import com.cskaoyan.order.dal.persistence.StockMapper;
import com.cskaoyan.order.form.CreateOrderRequest;
import com.cskaoyan.order.service.OrderCoreService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class OrderCoreServiceImpl implements OrderCoreService {

    @Autowired
    OrderMapper orderMapper;

    @Autowired
    OrderItemMapper orderItemMapper;

    @Autowired
    OrderShippingMapper orderShippingMapper;

    @Autowired
    OrderProcessPipelineFactory orderProcessPipelineFactory;

    @Autowired
    StockMapper stockMapper;


    /**
     * 创建订单的处理流程
     *
     * @param request
     * @return
     */
    @Override
    @Transactional
    public String createOrder(CreateOrderRequest request) {
        //创建pipeline对象
        TransOutboundInvoker invoker = orderProcessPipelineFactory.build(request);

        //启动pipeline
        invoker.start(); //启动流程（pipeline来处理）

        //获取处理结果
        AbsTransHandlerContext context = invoker.getContext();

        //从Context中获取订单Id
        String orderId = context.getOrderId();
        return orderId;
    }

    @Transactional
    @Override
    public void cancelOrder(String orderId) {

        // 修改订单状态
        Date date = new Date();
        Order order = new Order();
        order.setOrderId(orderId);
        order.setStatus(OrderConstants.ORDER_STATUS_TRANSACTION_CANCEL);
        order.setUpdateTime(date);
        order.setCloseTime(date);
        int i = orderMapper.updateByPrimaryKeySelective(order);
        if (i != 1) {
            throw new BizException(OrderRetCode.ORDER_NOT_EXIST.getCode(),
                    OrderRetCode.ORDER_NOT_EXIST.getMessage());
        }

        // 锁定库存解锁
        List<OrderItem> orderItems = orderItemMapper.queryByOrderId(orderId);
        for (OrderItem item : orderItems) {
            Stock stock = new Stock();
            stock.setItemId(item.getItemId());
            if (item.getStatus() == 1) {
                stock.setStockCount(item.getNum().longValue());
                stock.setLockCount(-item.getNum());
            }
            stockMapper.updateStock(stock);
        }
    }

    @Transactional
    @Override
    public void deleteOrder(String orderId) {
        Order order = orderMapper.selectByPrimaryKey(orderId);
        if (order != null) {
            // 删除订单表
            orderMapper.deleteByPrimaryKey(orderId);

            // 删除订单商品表 -> (0,1,2)商品数量退回, (1,2,3)退款
            List<OrderItem> orderItems = orderItemMapper.queryByOrderId(orderId);
            for (OrderItem item : orderItems) {
                orderItemMapper.deleteByPrimaryKey(item.getId());
            }

            // 0,1,2三种情况退库存
            switch (order.getStatus().intValue()) {
                case 0:
                case 1:
                case 2:
                    for (OrderItem orderItem : orderItems) {
                        Long itemId = orderItem.getItemId();
                        Stock stock = new Stock();
                        stock.setItemId(itemId);
                        stock.setStockCount(orderItem.getNum().longValue());
                        if (orderItem.getStatus() == 0) {
                            // 锁定的库存 --> 解锁
                            stock.setLockCount(-orderItem.getNum());
                        }
                        stockMapper.updateStock(stock);
                    }
            }

            // todo:1,2,3情况退款

            // 删除快递表
            Example example = new Example(OrderShipping.class);
            example.createCriteria().andEqualTo("orderId", orderId);
            orderShippingMapper.deleteByExample(example);
        }
    }

    @Override
    public void updateOrder(Integer status, String orderId) {
    }

}
